<?php
namespace App\Services\Activity;

use App\Exceptions\BasicException;
use App\Models\ActivityDB\Children2022RewardLog;
use App\Models\ActivityDB\Children2022Setting;
use App\Models\MainDB\MallOrders;
use App\Models\MainDB\MallProducts;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable as ThrowableAlias;

class ChildrenRewardService
{

    //获取活动
    public function getActivity(int $user_id)
    {
        $children2022Setting = new Children2022Setting();
        $setting = $children2022Setting->newQuery()->find(1);
        if (empty($setting)) {
            return new Collection();
        }
        $productIds = explode(',', $setting->product_ids);
        $products = (new MallProducts())->newQuery()->whereIn('id', $productIds)
            ->select('id','title','category_id','desc','picture','special')->get();
        data_set($setting, 'products', $products);
        //判断用户是否已领取
        $log = (new Children2022RewardLog())->newQuery()->where('user_id', $user_id)->first();
        data_set($setting,'is_received',empty($log)?0:1);
        return $setting->only(['start_at', 'end_at', 'products','is_received']);
    }

    /**
     * @throws BasicException
     */
    public function receive(int $user_id)
    {
        try {

            $children2022Setting = new Children2022Setting();
            $setting = $children2022Setting->newQuery()->find(1);

            if (time() < strtotime($setting->start_at) || time() > strtotime($setting->end_at)) {
                throw new BasicException(-1, '活动还未开始或已结束');
            }

            $childrenRewardLog = new Children2022RewardLog();
            $log = $childrenRewardLog->newQuery()->where('user_id', $user_id)->first();
            if ($log) {
                throw new BasicException(-1, '你已经领取过奖励了');
            }


            if (!app('redis')->set("children_receive:$user_id", 'lock', 'ex', 10, 'nx')) {
                throw new BasicException(-1);
            }

            $db = DB::connection('mysql');
            $activityDb = DB::connection('mysql_activity');
            $db->beginTransaction();
            $activityDb->beginTransaction();

            $this->addProduct($setting, $user_id);
            Children2022RewardLog::query()->insert([
                'user_id'           => $user_id,
                'desc'              => '六一奖励领取'
            ]);

            $activityDb->commit();
            $db->commit();

        } catch (ThrowableAlias $exception) {
            isset($db) && $db->rollBack();
            isset($activityDb) && $activityDb->rollBack();
            $code = $exception instanceof BasicException ? $exception->getCode() : 52013;
            $msg = $exception instanceof BasicException ? $exception->getMessage() : '';
            Log::info("儿童节活动领奖失败: {$user_id} :". $exception->getMessage());
            throw new BasicException($code, $msg);
        }
    }

    private function addProduct($setting, int $uid)
    {
        $product_ids = explode(',',$setting->product_ids);
        $products = (new MallProducts())->newQuery()->whereIn('id',$product_ids)->get(['id','category_id']);
        // 商品
        $products->each(function ($item) use ($uid) {
            if (!empty($item)) {
                (new MallOrders())->addProduct($uid, $item->id, 14, $item->category_id);
            }
        });
    }


}
